import datetime
import os
import re
import shutil
import time


class Demo(object):

    def __init__(self, data):
        # self.base_path = r'D:\Disktop\新建文件夹 (11)'
        self.base_path = r'E:\TxCollector\Transaction'
        self.data = data

    def read_history(self):
        if not os.path.exists(f"{self.data}.txt"):
            self.write_history("")
        with open(f"{self.data}.txt", 'r', encoding='utf-8') as read_history:
            file_history = read_history.read()
        read_history.close()
        return file_history

    def write_history(self, content):
        with open(f"{self.data}.txt", 'a', encoding='utf-8') as write_history:
            write_history.write(content + "\n")
        write_history.close()

    def read_index(self):
        with open(f"data.txt", 'r', encoding='utf-8') as read_data:
            file_index = read_data.read()
        read_data.close()
        return file_index

    def write_index(self, content):
        with open("data.txt", 'a', encoding='utf-8') as write_index:
            write_index.write(content + "\n")
        write_index.close()

    def del_index(self):
        with open("data.txt", 'w', encoding='utf-8') as del_index:
            del_index.write("")
        del_index.close()

    def get_data(self):
        '''
        获取所有门店当天文件数据
        :return: dict
        '''
        store_list = os.listdir(self.base_path)

        file_dict = {}
        for storeID in store_list:
            file_dir = rf"{self.base_path}\{storeID}\{self.data}"
            if os.path.exists(file_dir):
                file_list = os.listdir(file_dir)
                file_list = [rf"{file_dir}\{item}" for item in file_list]
                file_dict[storeID] = file_list
            else:
                print("directory not found：" + file_dir)
        return file_dict

    def deal_data(self, file):
        '''
        根据传过来的文件路径，筛选符合条件的文件
        :param file: 绝对路径
        :return:
        '''
        with open(file, 'r', encoding='utf=8') as r1:
            file_content = r1.read()
        r1.close()
        if ("<COUPON>" in file_content) and ("<szTaType>SA</szTaType>" in file_content) and ("<bIsLoyaltyECoupon>1</bIsLoyaltyECoupon>" not in file_content):
            lRetailStoreID = re.findall(r'<lRetailStoreID>(.*)</lRetailStoreID>', file_content)[0]
            lWorkstationNmbr = re.findall(r'<lTaCreatedWorkstationNmbr>(.*)</lTaCreatedWorkstationNmbr>', file_content)[0]
            SequenceNumber = re.findall(r'<lTaCreatedTaNmbr>(.*)</lTaCreatedTaNmbr>', file_content)[0]
            szTaCreatedDate = re.findall(r'<szTaCreatedDate>(.*)</szTaCreatedDate>', file_content)[0][:8]
            ScanCode = re.findall(r'<szScanCode>(.*)</szScanCode>', file_content)[0]
            if ScanCode not in self.read_history():
                content = '{"couponCode":"' + ScanCode + '","orderCode":"' + lRetailStoreID + lWorkstationNmbr + SequenceNumber + szTaCreatedDate + '"}'
                print(content)
                self.write_index(content)
                self.write_history(content)
            else:
                return

    def get_exe(self):
        '''
        调用优惠券接口工具
        :return:
        '''
        print("copy data.txt for dir :   START")
        shutil.copyfile("data.txt", r'E:\Wincor\Coupon\exe\data.txt')
        time.sleep(5)

        print("run deal coupon exe :   START")
        os.startfile(r"E:\Wincor\Coupon\exe\ManualUseCoupon.exe")  # 运行指定程序
        time.sleep(3)

        self.del_index()
        time.sleep(3)

    def main_task(self):
        files = demo.get_data()
        for item in files:
            print("deal store: " + str(item))
            for file in files[item]:
                demo.deal_data(file)


if __name__ == '__main__':
    data = input(r'input data:')
    demo = Demo(data)
    index = 0
    hour = int(datetime.datetime.today().strftime("%H"))
    while True:
        if hour > index:
            demo.main_task()
            demo.get_exe()
            index = hour
        else:
            hour = int(datetime.datetime.today().strftime("%H"))
            if hour == 0:
                index = 0
        time.sleep(50)
        print(hour, index)